<template>
	<div class="container">
		<!-- 顶部头像区域 -->
		<div class="avatar-section">
			<div class="avatar-wrapper">
				<img :src="form.user_avatar" alt="头像" class="avatar" />
				<div class="edit-icon" @click="triggerFileInput">
					<img style="width: 28px;height: 28px;" src="https://shalong.taiyanyue.top/images/bianjitx.png" alt="编辑" />
				</div>
				<div></div>
			</div>
		</div>
		<div style="font-size: 14px;text-align: center;margin-bottom: 6px;">{{ form.created_at }} 创建</div>
		<div style="font-size: 14px;text-align: center;margin-bottom: 25px;">NO.0000001</div>

		<!-- 表单区域 -->
		<div class="form-section">
			<div class="form-group required">
				<label>昵称</label>
				<input type="text" v-model="form.nick_name" placeholder="请输入昵称" />
			</div>

			<div class="form-group required">
				<label>姓名</label>
				<input type="text" v-model="form.full_name" placeholder="请输入真实姓名" />
			</div>

			<div class="form-group">
				<label>性别</label>
				<radio-group @change="handleGenderChange">
					<label class="radio-label" style="font-size: 13px;font-weight: 400;">
						<radio value="1" style="margin-right: 10px;" :checked="form.user_gender == 1" color="#339966" />
						男
					</label>
					<label class="radio-label" style="font-size: 13px;font-weight: 400;">
						<radio value="0" style="margin-right: 10px;" :checked="form.user_gender === 0"
							color="#339966" /> 女
					</label>
				</radio-group>
			</div>

			<div class="form-group">
				<label>手机</label>
				<input type="tel" v-model="form.user_phone" placeholder="请输入手机号码" />
			</div>

			<div class="form-group">
				<label>生日</label>
				<picker mode="date" :value="form.user_birthday" :start="startDate" :end="endDate"
					@change="handleDateChange">
					<view class="picker">
						{{form.user_birthday || '请选择生日'}}
					</view>
				</picker>
			</div>
		</div>
		<div class="form-section" style="font-size: 16px;font-weight: 550;" @click="fun()">用户隐私协议</div>
		<!-- 固定在底部的保存按钮 -->
		<div class="fixed-save-button">
			<button @click="handleSave">保存</button>
		</div>
	</div>
</template>

<script>
	import {
		getUserInfo,
		common_OSSFileUpload,
		user_userInfoEdit
	} from '@/api/login';
	export default {
		data() {
			const currentDate = this.getFormatDate(new Date())
			const startDate = '1900-01-01'

			return {
				startDate: startDate,
				endDate: currentDate,
				uploading: false,
				form: {
					nick_name: '',
					full_name: '',
					user_gender: '',
					user_phone: '',
					user_birthday: '',
					user_avatar: '',
					created_at:""
				}
			}
		},
		onShow() {
			this.menwe();
		},
		methods: {
			fun(){
				uni.navigateTo({
					url:'/pages/yhysxy'
				})
			},
			async menwe() {
				const res = await getUserInfo();
				const data = res.content.data;
				this.form = {
					nick_name: data.nick_name || '',
					full_name: (data.user_last_name || '') + (data.user_first_name || ''),
					user_gender: data.user_gender !== undefined ? data.user_gender : '',
					user_phone: data.user_phone || '',
					user_birthday: data.user_birthday || '',
					user_avatar: data.user_avatar || '',
					created_at:data.created_at || '',
				};
			},
			triggerFileInput() {
				if (this.uploading) return;

				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						// 先显示本地选择的图片
						this.form.user_avatar = tempFilePath;
						// 上传图片
						this.uploadAvatar(tempFilePath);
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
					}
				});
			},
			async uploadAvatar(filePath) {
				this.uploading = true;
				uni.showLoading({
					title: '上传中...'
				});

				try {
					const res = await uni.uploadFile({
						url: 'https://shalong.taiyanyue.top/api/common/OSSFileUpload',
						filePath: filePath,
						name: 'file',
						formData: {},
						header: {
							// 'Authorization': 'Bearer ' + uni.getStorageSync('token')
						}
					});

					const data = JSON.parse(res[1].data);
					if (data.code === 200 && data.content && data.content.path) {
						this.form.user_avatar = data.content.path;
						uni.showToast({
							title: '上传成功',
							icon: 'none'
						});
					} else {
						throw new Error(data.message || '上传失败');
					}
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				} finally {
					this.uploading = false;
					uni.hideLoading();
				}
			},
			handleGenderChange(e) {
				this.form.user_gender = Number(e.detail.value);
			},
			handleDateChange(e) {
				this.form.user_birthday = e.detail.value
			},
			getFormatDate(date) {
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			async handleSave() {
				if (!this.form.nick_name) {
					uni.showToast({
						title: '昵称是必填项',
						icon: 'none'
					})
					return
				}
				
				if (!this.form.full_name || this.form.full_name.length < 2) {
					uni.showToast({
						title: '姓名至少需要2个字符',
						icon: 'none'
					})
					return
				}
				
				// 拆分姓名为姓和名
				const name = this.form.full_name.trim();
				let lastName = '';
				let firstName = '';
				
				if (name.length > 1) {
					lastName = name.substring(0, 1); // 取第一个字符作为姓
					firstName = name.substring(1);  // 剩余字符作为名
				} else {
					// 如果用户只输入了一个字，我们将其全部作为名
					firstName = name;
				}

				const data = await user_userInfoEdit({
					nick_name: this.form.nick_name,
					user_last_name: lastName,
					user_first_name: firstName,
					user_gender: this.form.user_gender,
					user_avatar: this.form.user_avatar,
					user_birthday: this.form.user_birthday
				})
				if(data.code==200){
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f4f4f4;
		min-height: 100vh;
		padding: 20px 0 80px;
		/* 底部留出保存按钮的空间 */
		box-sizing: border-box;
		position: relative;
	}

	.avatar-section {
		display: flex;
		justify-content: center;
		margin-bottom: 20px;
		padding-top: 20px;
	}

	.avatar-wrapper {
		position: relative;
		width: 90px;
		height: 90px;
	}

	.avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		object-fit: cover;
		border: 2px solid #fff;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.edit-icon {
		position: absolute;
		right: 0;
		bottom: 0;
		width: 30px;
		height: 30px;
		background-color: #fff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
		cursor: pointer;
	}

	.edit-icon img {
		width: 16px;
		height: 16px;
	}

	.form-section {
		background-color: #fff;
		margin: 0 15px 20px;
		padding: 15px;
		border-radius: 8px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.form-group {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		padding-bottom: 15px;
		border-bottom: 1px solid #f0f0f0;
	}

	.form-group:last-child {
		border-bottom: none;
		margin-bottom: 0;
		padding-bottom: 0;
	}

	.form-group label {
		width: 60px;
		font-size: 16px;
		color: #333;
		font-weight: 550;
		flex-shrink: 0;
	}

	.form-group input[type="text"],
	.form-group input[type="tel"],
	.form-group input[type="date"] {
		flex-grow: 1;
		height: 40px;
		padding: 0 10px;
		font-size: 16px;
		box-sizing: border-box;
		background-color: transparent;
		outline: none;
	}

	.form-group.required label::after {
		content: ' *';
		color: red;
	}

	/* 单选按钮样式 */
	.radio-label {
		display: inline-flex;
		align-items: center;
		margin-right: 15px;
		font-size: 14px;
	}

	/* 选择器样式 */
	.picker {
		flex: 1;
		height: 40px;
		line-height: 40px;
		font-size: 16px;
		color: #666;
	}

	/* 固定底部按钮 */
	.fixed-save-button {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10px 15px;
	}

	.fixed-save-button button {
		width: 100%;
		height: 44px;
		background-color: #339966;
		color: white;
		border: none;
		border-radius: 20px;
		font-size: 16px;
		font-weight: bold;
		cursor: pointer;
	}

	.fixed-save-button button:active {
		opacity: 0.8;
	}
</style>